declare global {
	interface Window {
		plus?: {
			webview: {
				currentWebview: () => PlusWebview
			}
			key: {
				addEventListener: (
					event: string,
					callback: () => void,
					capture?: boolean
				) => void
				removeEventListener: (
					event: string,
					callback: () => void,
					capture?: boolean
				) => void
			}
			nativeUI: {
				toast: (
					message: string,
					options: { duration: "short" | "long" }
				) => void
			}
			runtime: {
				quit: () => void
			}
		}
		__backButtonHandlerInitialized?: boolean // 全局初始化标记
	}
}

interface PlusWebview {
	canBack: (callback: (e: { canBack: boolean }) => void) => void
	back: () => void
}

/**
 * 初始化返回按钮处理逻辑（修复版）
 */
export function initBackButtonHandler() {
	// 防止重复初始化
	if (window.__backButtonHandlerInitialized) return
	window.__backButtonHandlerInitialized = true

	let firstPressTime: number | null = null
	let backHandler: (() => void) | null = null

	const cleanup = () => {
		if (backHandler && window.plus) {
			window.plus.key.removeEventListener("backbutton", backHandler)
		}
		firstPressTime = null
	}

	document.addEventListener("plusready", () => {
		if (!window.plus) return

		const webview = window.plus.webview.currentWebview()
		let toastShown = false // 本地toast显示状态

		backHandler = () => {
			webview.canBack(e => {
				if (e.canBack) {
					webview.back()
				} else {
					const now = Date.now()

					if (firstPressTime === null) {
						firstPressTime = now
						if (!toastShown) {
							window.plus?.nativeUI.toast("再按一次退出应用", {
								duration: "short",
							})
							toastShown = true
						}
						setTimeout(() => {
							firstPressTime = null
							toastShown = false
						}, 2000)
					} else if (now - firstPressTime <= 2000) {
						cleanup()
						window.plus?.runtime.quit()
					}
				}
			})
		}

		window.plus.key.addEventListener("backbutton", backHandler)

		// 页面卸载时清理
		window.addEventListener("unload", cleanup)
	})
}
